package com.woman.beautylive.presentation.ui.room.publish;

import android.hardware.Camera;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.woman.beautylive.data.bean.AnchoBean;
import com.woman.beautylive.data.bean.BaseResponse;
import com.woman.beautylive.data.bean.CameraSize;
import com.woman.beautylive.data.bean.GetFriendBean;
import com.woman.beautylive.data.bean.LoginInfo;
import com.woman.beautylive.domain.AnchorManager;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseObserver;
import com.woman.beautylive.presentation.ui.base.BasePresenter;
import com.woman.beautylive.util.L;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Muyangmin
 * @since 1.0.0
 */
public class PublishFragmentPresenter extends BasePresenter<PublishFragmentUiInterface>
        implements CameraSizePicker {

    private AnchorManager anchorManager;

    public PublishFragmentPresenter(PublishFragmentUiInterface uiInterface) {
        super(uiInterface);
        anchorManager = new AnchorManager();
    }

    public void startLive(){
        Subscription subscription = anchorManager.startLive(LocalDataManager.getInstance().getLoginInfo().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<Object>>(getUiInterface()) {
                    @Override
                    public void onSuccess(BaseResponse<Object> response) {
                        //Empty
                    }
                });
        addSubscription(subscription);
    }

    public void stopLive(){
        Subscription subscription = anchorManager.stopLive(LocalDataManager.getInstance().getLoginInfo().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<Object>>(getUiInterface()) {
                    @Override
                    public void onSuccess(BaseResponse<Object> response) {
                        //Empty
                    }
                });
        addSubscription(subscription);
    }

    public void saveFrontCameraSize(@NonNull CameraSize front) {
        LocalDataManager.getInstance().saveCameraSize(front, true);
    }

    public void saveBackCameraSize(@NonNull CameraSize back) {
        LocalDataManager.getInstance().saveCameraSize(back, false);
    }

    @Nullable
    public CameraSize getBackCameraSize() {
        return LocalDataManager.getInstance().getCameraSize(false);
    }

    @Nullable
    public CameraSize getFrontCameraSize() {
        return LocalDataManager.getInstance().getCameraSize(true);
    }

    @NonNull
    @Override
    public CameraSize selectBestSize(List<Camera.Size> list) {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("Null or empty list not allowed!");
        }
        LinkedList<Camera.Size> candidateSizes = new LinkedList<>();
        LinkedList<CameraSize> whiteListItems = new LinkedList<>();
        for (Camera.Size size : list) {
            if (candidateSizes.isEmpty()) {
                candidateSizes.add(size);
                continue;
            }

            //add white list adjustment
            for (CameraSize item : WHITE_LIST) {
                if (item.height == size.height && item.width == size.width) {
                    whiteListItems.add(item);
                }
            }

            int widthDiff = Math.abs(size.width - STD_WIDTH);
            int widthDiffInCandidates = Math.abs(candidateSizes.get(0).width - STD_WIDTH);
            if (widthDiff < widthDiffInCandidates) {
                candidateSizes.clear();
                candidateSizes.add(size);
            } else if (widthDiff == widthDiffInCandidates) {
                candidateSizes.add(size);
            }
            //else : do nothing
        }

        //优先选择白名单中的分辨率
        if (!whiteListItems.isEmpty()){
            L.i("PickSize", "Using white list item!");
            //按照与宽度的差值排序
            Collections.sort(whiteListItems, new Comparator<CameraSize>() {
                @Override
                public int compare(CameraSize lhs, CameraSize rhs) {
                    int lDiff = Math.abs(STD_WIDTH-lhs.width);
                    int rDiff = Math.abs(STD_WIDTH-rhs.width);
                    return Integer.valueOf(lDiff).compareTo(rDiff);
                }
            });
            return whiteListItems.get(0);
        }
        L.d("PickSize", "candidates:%s", candidateSizes);

        Camera.Size finalSize = null;
        for (Camera.Size size : candidateSizes) {
            if (finalSize == null) {
                finalSize = size;
                continue;
            }
            int heightDiff = Math.abs(size.width - STD_HEIGHT);
            int heightDiffFinal = Math.abs(finalSize.width - STD_HEIGHT);
            //Here == is impossible
            if (heightDiff < heightDiffFinal) {
                finalSize = size;
            }
        }
        //Here finalSize won't be null.
        if (finalSize == null) {
            throw new IllegalStateException("Final size shouldn't be null!");
        }
        CameraSize wrapper = new CameraSize(finalSize.width, finalSize.height);
        L.i("PickSize", "Finally use size %s", wrapper);
        return wrapper;
    }
    //    小伙伴
    public void loadFriendList(){
        Subscription subscription = anchorManager.getFriendList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<GetFriendBean>>>(getUiInterface()) {
                    @Override
                    public void onSuccess(BaseResponse<List<GetFriendBean>> response) {
                        getUiInterface().showFriendList(response.getData());
                    }
                });
        addSubscription(subscription);
    }
}
